<script setup lang="ts" name="inspection-artificial">
import {
  defineComponent,
  onMounted,
  onActivated,
  reactive,
  ref,
  toRaw,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
// import { accountList } from "@/api/server_set_patrol";
import {
  getInspectionAccountLis,
  uploadFile,
  getAllInspectionPersonList,
} from "@/api/server_bill";
import {
  cameraList,
  getIserList,
  getDeptTree,
  getActionList,
  cameraSave,
  delCamera,
  getAllDeptCameraTree,
} from "@/api/server_set_camera";
import {
  addInspectionPersonTask,
  getInspectionPersonList,
  getInspectionAccountList,
  getInspectionPersonTaskList,
  deleteInspectionPersonTaskt,
} from "@/api/server_artificial";

/* data */
// 引入图片
import img1 from "@/assets/image/01 (1).png";
import img2 from "@/assets/image/01 (2).png";
import img3 from "@/assets/image/01 (3).png";
import img4 from "@/assets/image/01 (4).png";
import img5 from "@/assets/image/01 (5).png";
const router = useRouter();
const height = ref(0);
const tempIndex = ref();
const isEdit = ref(false);
const isBig = ref(false);
const dialogVisible_add = ref(false);
const dialogVisible_map = ref(false);

const listParams = ref({
  page: 1,
  pageSize: 20,
});
const List = ref([]);

const dataList = ref({
  inspectionPersonMap: {},
  list: [],
  page: "",
  pageSize: "",
  result: "",
  total: "",
});

const dataList1 = ref({
  userEN: "人工消防巡检",
});

const total = ref(0);
const value3 = ref("");

const deptOptions = ref<any>([]);
const userList = ref<any>([]);
const actionList: any = ref([]);

const formData = ref<any>({
  name: "",
  inspectionPersonIds: [],
  // coordinate: "巡检点位置",
  account_id: "",
  gmtExec: "",
  content: "",
  // inspectionPersonId: "",
  // gmt_exec: "",
});

// 转换字符
// const inspectid = ref('')
// const inspectids = ()=>{
//   inspectid.value = formData.value.inspectionPersonIds.toString()

// }

const cascaderProps = reactive({
  label: "label",
  value: "id",
  children: "children",
  checkStrictly: true,
  emitPath: false,
});
const currentPage = ref(1);

/* methods */
const addItem = () => {
  isEdit.value = false;
  formData.value = {};
  dialogVisible_add.value = true;
};
const editdata = ref([])
const edit = (data: any) => {
  editdata.value = data.inspectionPersonIds
  
  change(editdata.value)
  //  formData.value.inspection_person_ids.push(formData.value.inspectionPersonIds)
  isEdit.value = true;
  formData.value = {
    ...data,
  };

  formData.value.account_id = formData.value.account_id;
  formData.value.coordinate = formData.value.coordinate
    ? formData.value.coordinate.split(",")
    : [];
  // let related_camera_ids = formData.value.related_camera_ids
  //   ? formData.value.related_camera_ids.split(",")
  //   : [];
  // formData.value.relatedCameraIds = related_camera_ids.map((v: any) => {
  //   return "camera_" + v;
  // });
  dialogVisible_add.value = true;
};
const remove = (data: any) => {
  ElMessageBox.confirm(
    `<span>确定要删除 <i style="color:#58B2C5;">${data.name}</i> 吗</span>`,
    "提 示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: true,
      type: "warning",
    }
  ).then(async () => {
    let res: any = await deleteInspectionPersonTaskt({
      id: data.inspection_person_task_id,
    });

    if (res.result == "success") {
      getList(0);
      ElMessage({
        type: "success",
        message: "删除成功!",
      });
    }
  });
};

const getUser = async () => {
  let res = await getIserList({});
  if (res.result == "success") {
    userList.value = res.list;
  }
};
// 获取巡检人
const getDeptInfo = async () => {
  let res: any = await getInspectionAccountLis({});

  if (res.result == "success") {
    deptOptions.value = res.list;
    console.log('巡检人',res.list);
    
  }
};
// 获取巡检点
const getActionListInfo = async () => {
  let res: any = await getAllInspectionPersonList({});
  if (res.result == "success") {
    actionList.value = res.list;
  }
  console.log("巡检点", actionList.value);
};

// 巡检点数组
const arrAction = ref([]);

const arrActionlist = ref([]);
const arrFilelist = ref<any>([]);
const arrActionall = ref();
const change = (val: any) => {
  arrFilelist.value = []
  

  for (var i in actionList.value) {
    if (val.indexOf(actionList.value[i].inspection_person_id) > -1) {
      actionList.value[i].files.forEach((item: any) => {


        arrFilelist.value.push({
          id: actionList.value[i].inspection_person_id,
          url: item,
        });
        // arrFilelist.value.push(arrFilelist.value)
        // console.log('arrFilelistitem.value',arrFilelist.value);

      });
    }
  }
};
const delFilelist = ref([]);
// const removeTag = (val: any) => {
//   delFilelist.value = arrFilelist.value.filter((item:any) => item.id != val)

//   arrFilelist.value = delFilelist.value

// };
// const clear = (val: any) => {
//   delFilelist.value = []
// };

const passwordShow = async (data: any, type: any) => {
  data.passwordShow = type;
};
const handleSizeChange = (val: number) => {
  listParams.value.pageSize = val;
  getList(currentPage.value);
};
const handleCurrentChange = (val: number) => {
  getList(val);
};

// 下拉选择

const urlimgAll = ref<any>([]);
const urlimgAllvalue = ref<any>([]);
const srcList = ref<any>([]);
// const valuelabel = ref<any>([]);

// 添加下拉框

// 删除下拉框
const srcListnew = ref([]);

const mapClick = (event: any) => {
  let offsetX = event.offsetX;
  let offsetY = event.offsetY;
  function setMapIndex(x: number, y: number) {
    let indexPoint: any = document.querySelector(".index-point");
    indexPoint.style.top = `${y}px`;
    indexPoint.style.left = `${x}px`;
    indexPoint.style.display = `block`;
    tempIndex.value = `${x},${y}`;
  }
  setMapIndex(offsetX, offsetY);
};
const doubleclick = (event: any) => {
  isBig.value = !isBig.value;
  if (!isBig.value) {
    setMap();
    return;
  }
  let offsetX = event.offsetX;
  let offsetY = event.offsetY;
  let mapBlock: any = document.querySelector(".setMapBlock-body");
  let mapId: any = document.querySelector(".setMapBlock");
  let mapBlockHeight = mapBlock.clientHeight;
  let mapBlockWidth = mapBlock.clientWidth;
  let mapIdHeight = mapId.clientHeight;
  let mapIdWidth = mapId.clientWidth;
  let left = -event.offsetX + mapBlockWidth / 2;
  let top = -event.offsetY + mapBlockHeight / 2;
  setTimeout(() => {
    if (left > 0) left = 0;
    if (left < mapBlockWidth - mapIdWidth) left = mapBlockWidth - mapIdWidth;
    if (top > 0) top = 0;
    if (top < mapBlockHeight - mapIdHeight) top = mapBlockHeight - mapIdHeight;
    mapId.style.transform = `scale(${1})`;
    mapId.style.left = `${left}px`;
    mapId.style.top = `${top}px`;
  }, 100);
  mapId.oncontextmenu = function () {
    return false;
  };

  mapId.addEventListener("mousedown", function (event: any) {
    event.stopPropagation();
    var code = event.which;
    if (code != 3 || !isBig.value) {
      return;
    }
    let left = parseInt(mapId.style.left);
    let top = parseInt(mapId.style.top);
    let ol = event.clientX;
    let ot = event.clientY;
    document.onmousemove = function (ev) {
      let l = left + ev.clientX - ol;
      let t = top + ev.clientY - ot;
      if (l > 0) l = 0;
      if (l < mapBlockWidth - mapIdWidth) l = mapBlockWidth - mapIdWidth;
      if (t > 0) t = 0;
      if (t < mapBlockHeight - mapIdHeight) t = mapBlockHeight - mapIdHeight;
      mapId.style.left = l + "px";
      mapId.style.top = t + "px";
    };
    document.onmouseup = function () {
      document.onmousemove = null;
    };
  });
};
const setMap = () => {
  let mapBlock: any = document.querySelector(".setMapBlock-body");
  let mapId: any = document.querySelector(".setMapBlock");
  let mapBlockHeight = mapBlock.clientHeight;
  let mapBlockWidth = mapBlock.clientWidth;
  let mapIdHeight = mapId.clientHeight;
  let mapIdWidth = mapId.clientWidth;
  let zoomVal = mapBlockHeight / mapIdHeight;
  let left = (mapBlockWidth - mapIdWidth) / 2;
  let top = (mapBlockHeight - mapIdHeight) / 2;
  mapId.style.transform = `scale(${zoomVal})`;
  mapId.style.left = `${left}px`;
  mapId.style.top = `${top}px`;
  mapId.oncontextmenu = function () {
    return false;
  };
};
const setIndex = () => {
  formData.value.coordinate = tempIndex.value;
  dialogVisible_map.value = false;
};
const allDeptCameraTree = ref<any>([]);
const getAllDeptCameraTree_ = async () => {
  let res = await getAllDeptCameraTree({});
  allDeptCameraTree.value = res.data || [];
};
const customNodeDisabled = (data: any, node: Node) => {
  let children = data.children || [];
  if (data.type == "dept" && children.length == 0) {
    return true;
  }
};

// 添加巡检任务
const confirmAdd = async () => {
  // inspectids()
  let res: any = await addInspectionPersonTask({
    id: isEdit ? formData.value.inspection_person_task_id : 0,
    name: formData.value.name,
    inspectionPersonIds: formData.value.inspectionPersonIds,
    // inspectionPersonIds: formData.value.action_list ? formData.value.inspectionPersonIds.split(",") : [],
    // coordinate: "巡检点位置",
    accountId: formData.value.account_id,
    gmtExec: formData.value.gmt_exec,
    content: formData.value.content,
  });
  dialogVisible_map.value = false;
  if (res.result == "success") {
    dialogVisible_add.value = false;
    getList(0);
  }
  console.log('巡检点',formData.value.inspectionPersonIds);
  
};

// 获取巡检任务列表
const getList = async (page: number) => {
  let res: any = await getInspectionPersonTaskList({
    ...toRaw(listParams.value),
    page,
  });
  if (res.result == "success") {
    // 巡检任务列表
    dataList.value.list = res.list;
    // 巡检点位列表
    // dataList.value = res.list;
    total.value = Number(res.total);
    console.log('巡检任务列表',dataList.value.list);
    
  }
};

// const getTaskList = async () => {
//   let res = await getInspectionPersonTaskList({});
//   dataList.value = res.list;
// };

// 巡检频率
const value1 = ref("");
const value2 = ref("");
const options = [
  {
    value: "Option1",
    label: "星期一",
  },
  {
    value: "Option2",
    label: "星期二",
  },
  {
    value: "Option3",
    label: "星期三",
  },
  {
    value: "Option4",
    label: "星期四",
  },
  {
    value: "Option5",
    label: "星期五",
  },
  {
    value: "Option5",
    label: "星期六",
  },
  {
    value: "Option5",
    label: "星期日",
  },
];
const options1 = [
  {
    value: "Option1",
    label: "1号",
  },
  {
    value: "Option2",
    label: "2号",
  },
  {
    value: "Option3",
    label: "3号",
  },
  {
    value: "Option4",
    label: "4号",
  },
  {
    value: "Option5",
    label: "5号",
  },
  {
    value: "Option5",
    label: "6号",
  },
  {
    value: "Option5",
    label: "7号",
  },
  {
    value: "Option5",
    label: "8号",
  },
  {
    value: "Option5",
    label: "9号",
  },
  {
    value: "Option5",
    label: "10号",
  },
  {
    value: "Option5",
    label: "11号",
  },
  {
    value: "Option5",
    label: "12号",
  },
  {
    value: "Option5",
    label: "13号",
  },
  {
    value: "Option5",
    label: "14号",
  },
  {
    value: "Option5",
    label: "15号",
  },
  {
    value: "Option5",
    label: "16号",
  },
  {
    value: "Option5",
    label: "17号",
  },
  {
    value: "Option5",
    label: "18号",
  },
  {
    value: "Option5",
    label: "19号",
  },
  {
    value: "Option5",
    label: "20号",
  },
  {
    value: "Option5",
    label: "21号",
  },
  {
    value: "Option5",
    label: "22号",
  },
  {
    value: "Option5",
    label: "23号",
  },
  {
    value: "Option5",
    label: "24号",
  },
  {
    value: "Option5",
    label: "25号",
  },
  {
    value: "Option5",
    label: "26号",
  },
  {
    value: "Option5",
    label: "27号",
  },
  {
    value: "Option5",
    label: "28号",
  },
  {
    value: "Option5",
    label: "29号",
  },
  {
    value: "Option5",
    label: "30号",
  },
  {
    value: "Option5",
    label: "31号",
  },
];

// 生命周期
onMounted(() => {
  let pageTable: any = document.querySelector(".page-table");
  height.value = pageTable.clientHeight;
  getList(1);
  getUser();
  getDeptInfo();
  getActionListInfo();
  getAllDeptCameraTree_();
  // getTaskList();
  
  
});
</script>

<template>
  <div class="camera-page">
    <div class="page-top">
      <h4>巡检任务配置</h4>
      <el-button type="primary" size="small" @click="addItem"
        >新增巡检任务</el-button
      >
    </div>
    <div class="page-table">
      <el-table
        ref="table"
        v-if="height"
        :data="dataList.list"
        :height="height"
      >
        <el-table-column
          width="120px"
          label="序号"
          prop="inspection_person_task_id"
        ></el-table-column>
        <el-table-column label="巡检任务名称" prop="name"></el-table-column>
        <el-table-column
          label="巡检点位"
          prop="inspectionPersonNames"
        ></el-table-column>
        <el-table-column label="巡检日期" prop="gmt_exec"></el-table-column>
        <el-table-column label="负责人" prop="accountName"></el-table-column>
        <el-table-column label="电话" prop="phone"></el-table-column>
        <el-table-column label="内容" prop="content"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button link size="small" @click="edit(row)">编辑</el-button>
            <el-button link size="small" @click="remove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-model:currentPage="currentPage"
        :page-sizes="[20, 30, 50, 70]"
        :page-size="listParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="isEdit ? '编辑巡检任务' : '新增巡检任务'"
      v-model="dialogVisible_add"
      width="650px"
    >
      <el-form ref="form" :model="formData" label-width="120px">
        <el-form-item label="序号" v-if="isEdit">
          <el-input
            type="text"
            disabled
            placeholder="巡检编号"
            v-model="formData.inspection_person_task_id"
          ></el-input>
        </el-form-item>
        <el-form-item label="巡检任务名称">
          <el-input
            type="text"
            placeholder="请输入巡检任务名称"
            v-model="formData.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="巡检点名称">
          <el-select
            @change="change"
            style="width: 100%"
            filterable
            clearable
            multiple
            v-model="formData.inspectionPersonIds"
            placeholder="请选择巡检点"
          >
            <el-option
              :label="item.name"
              :value="item.inspection_person_id"
              :key="index"
              v-for="(item, index) in actionList"
            >
              <span style="float: left">{{ item.name }}</span>
              <span
                style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                "
                >{{ item.coordinate }}</span
              >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="巡检坐标">
          <el-input
            type="text"
            placeholder="坐标"
            v-model="formData.coordinate"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="图片">
          <div class="arrFilelist">
            <img
              v-for="(item, index) in arrFilelist"
              :key="index"
              :src="item.url"
            />
            <!-- <el-image
            :src="arrFilelist[0]"
            style="width: 100px; height: 100px"
            :initial-index="1"
            :preview-src-list="arrFilelist"
            fit="cover"
          /> -->
          </div>
        </el-form-item>
        <el-form-item label="巡检频率">
          <el-select v-model="value1" clearable placeholder="星期">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            style="padding: 0 0 0 15px"
            v-model="value2"
            clearable
            placeholder="月份"
          >
            <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="巡检任务负责人">
          <el-select
            filterable
            clearable
            style="width: 80%"
            v-model="formData.account_id"
            placeholder="请选择"
          >
            <el-option
              :value="c.account_id"
              :label="c.username"
              :key="index"
              v-for="(c, index) in deptOptions"
            >
              <span style="float: left">{{ c.username }}</span>
              <span
                style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                "
                >{{ c.phone }}</span
              >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="负责人电话">
          <el-select
            style="width: 100%"
            filterable
            clearable
            v-model="formData.account_id"
            placeholder="请选择"
          >
            <el-option
              :label="item.username"
              :value="item.username"
              :key="index"
              v-for="(item, index) in deptOptions"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="巡检时间">
          <el-date-picker
            v-model="formData.gmt_exec"
            type="date"
            placeholder="选择巡检时间"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="内容">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入巡检内容"
            v-model="formData.content"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible_add = false">取 消</el-button>
          <el-button type="primary" @click="confirmAdd">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设置地图 -->
    <el-dialog
      :close-on-click-modal="false"
      title="提示"
      :destroy-on-close="true"
      v-model="dialogVisible_map"
      width="800"
    >
      <div class="setMapBlock-body">
        <div id="rightClickDiv">
          <div class="addProductSpan liHover">选择位置</div>
        </div>
        <div class="setMapBlock" @dblclick="doubleclick" @click="mapClick">
          <img src="@/assets/image/home/map.png" />
          <div class="index-point" style="top: 1px; left: 1px">
            <img src="@/assets/image/home/camera.png" />
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible_map = false">取 消</el-button>
          <el-button type="primary" @click="setIndex()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.camera-page {
  width: 100%;
  height: 100%;

  .page-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .page-table {
    margin: 16px 0;
    height: calc(100% - 100px);
  }
}

.setMapBlock-body {
  width: 100%;
  height: 500px;
  overflow: hidden !important;
  position: relative;
  border: 1px solid #000;
}

.camera-page {
  width: 100%;
  height: 100%;

  .page-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .page-table {
    margin: 16px 0;
    height: calc(100% - 100px);
  }
}

.setMapBlock-body {
  width: 100%;
  height: 500px;
  overflow: hidden !important;
  position: relative;
  border: 1px solid #000;
}

.setMapBlock {
  display: inline-block;
  position: absolute;
  cursor: pointer;
}

.setMapBlock .index-point {
  width: 0;
  height: 0;
  position: absolute;
  display: none;
}

.setMapBlock .index-point img {
  position: absolute;
  width: 144px;
  left: -144px;
  bottom: 0;
}

#rightClickDiv {
  display: none;
  position: fixed;
  width: 80px;
  border: 1px solid #d8d8d8;
  box-shadow: 3px 3px 5px #dadada;
  z-index: 10001;
  background-color: white;
}

#rightClickDiv > .liHover {
  position: relative;
  height: 30px;
  font-size: 16px;
  line-height: 30px;
  text-align: center;
  cursor: pointer;
}

.liHover:hover {
  /*鼠标悬浮样式*/
  background-color: #e1e1e1;
}

.camera-page-label-img-box {
  margin: 5px;
}
.arrFilelist {
  width: 600px;
  display: flex;
  flex-wrap: wrap;
  overflow: auto;
  background-color: #131313;
}
.arrFilelist img {
  width: 80px;
  height: 60px;
}
</style>
